import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:seedfour/app/models/user_account_alloc_entity.dart';

import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class DepositLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final mmkv = MMKV.defaultMMKV();
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();
  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  var isLoading = true.obs;
  var isListLoading = false.obs;
  var deposit = '0.00'.obs;
  var tabTitles = ['全部', '未结算', '已结算'].obs;
  var bottomTips = ''.obs;
  var depositList = <UserAccountAllocData>[].obs;
  late TabController tabController;
  late ScrollController scrollController;

  var role = ''.obs;

  final pageSize = 20;
  int _page = 1;

  @override
  void onInit() {
    super.onInit();

    role.value = commonService.getRole();

    tabController = TabController(length: tabTitles.length, vsync: this);
    tabController.addListener(() {
      if (tabController.index.toDouble() == tabController.animation?.value) {
        _page = 1;
        depositList.clear();
        isListLoading.value = true;
        _getAccountInfo(_page);
      }
    });

    scrollController = ScrollController();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        bottomTips.value = loadingTip;
        _getAccountInfo(_page);
      }
    });

    _getAccountInfo(_page);
  }

  void onClickCase(String caseId) {
    Get.toNamed(RouteGet.caseDetail, arguments: caseId);
  }

  void _getAccountInfo(int page) {
    apiService.getAllocInfo(page, pageSize, role.value, 3).then((value) => {
          isLoading.value = false,
          isListLoading.value = false,
          _page++,
          if (value != null)
            {
              deposit.value = value.totalRemain.toString(),
              if (value.data.isNotEmpty) {depositList.addAll(value.data)},
              if (value.data.length < pageSize)
                {bottomTips.value = noMoreTip}
              else
                {bottomTips.value = loadingTip},
            }
          else
            {bottomTips.value = noMoreTip}
        });
  }

  @override
  void onClose() {
    tabController.dispose();
    scrollController.dispose();
    super.onClose();
  }
}
